const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8081 });

server.on('connection', (ws) => {
    console.log("New client connected");

    ws.on('message', (message) => {
        console.log(`Received: ${message}`);

        console.log(`clients num: ${server.clients.size}`);

        // 广播收到的消息给所有客户端
        server.clients.forEach(client => {
            console.log(`--11- ${client.readyState}`);
            if (/*client !== ws &&*/ client.readyState === WebSocket.OPEN) {
                client.send(message);
            }
        });
    });

    ws.on('close', () => {
        console.log('Client disconnected');
    });

    ws.send('welcome to  WebSocket server!');
});

console.log(`WebSocket server is running on ws://localhost:8081`);